<template>
	<uv-navbar
	  :fixed="false"
	  :title="title"
	  left-arrow
	  @leftClick="$onClickLeft"
	/>
	<view>
		<view class="set-box bg-white">
			<uv-form :model="form" ref="uForm" :rules="rules" labelPosition="top" :errorType="errorType" labelWidth="100">
				<uv-form-item  label="客户:" @click="type == 'edit' ? '' : selectShow()" prop="customerName" required >
					<uv-input disabledColor="#ffffff" :disabled="type == 'edit' ? true : false" v-model="form.customerName" placeholder="选择客户" >
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item required label="姓名:"  prop="name">
					<uv-input v-model="form.name" />
				</uv-form-item>
				<uv-form-item  label="联系手机:"  prop="mobile">
					<uv-input v-model="form.mobile" type="number"/>
				</uv-form-item>
				<uv-form-item  label="联系电话:" >
					<uv-input v-model="form.telephone"  type="number"  />
				</uv-form-item>
				<uv-form-item  label="邮箱:"  >
					<uv-input v-model="form.email" />
				</uv-form-item>
				<uv-form-item  label="微信:"  >
					<uv-input v-model="form.wechat" />
				</uv-form-item>
				<uv-form-item  label="职务:"  >
					<uv-input v-model="form.post" />
				</uv-form-item>
				<uv-form-item  label="生日:"  @click="dateShow" >
					<uv-input  v-model="birthdayName" placeholder="选择生日"  disabled disabledColor="#ffffff" >
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item  label="性别:"  >
					<uv-radio-group v-model="form.sex" >
						<uv-radio v-for="(item, index) in sexList"  :key="index"  :name="item.name">
							{{ item.text }}
						</uv-radio>
					</uv-radio-group>
				</uv-form-item>
				<uv-form-item  label="决策人:"  >
					<uv-radio-group v-model="form.decision" >
						<uv-radio v-for="(item, index) in typeList"  :key="index" :name="item.name">
							{{ item.text }}
						</uv-radio>
					</uv-radio-group>
				</uv-form-item>
				<uv-form-item label="地址:" >
					<uv-input  v-model="form.detailAddress" placeholder="请填写地址" />
				</uv-form-item>
				<uv-form-item  label="下次联系时间 :"  @click="createTimeShow">
					<uv-input  disabled disabledColor="#ffffff" v-model="nextTime" placeholder="选择下次联系时间" >
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item  label="备注 :" >
					<uv-textarea v-model="form.remark" placeholder="请输入备注"></uv-textarea>
				</uv-form-item>
			</uv-form>
			<!-- 底部浮动按钮 -->
			<view class="bottom-btn u-border-top" >
				<uv-button @click="submit" color="#09b4f1">提交</uv-button>
			</view>
		</view>
		<uv-datetime-picker ref="dateShowRef" v-model="timeValue1" mode="datetime" @confirm="change"></uv-datetime-picker>
		<!-- 选择客户弹窗 -->
		<uv-popup  mode="bottom" round="38"  ref="selectShowRef" >
			<view class="popup-content">
				<view class="popup-title">
					<view class=""  style="width: 45px;">
					</view>
					<text class="">选择客户</text> 
					<view class="" @click="selectShowClose" style="width: 45px;">
						<uv-icon name="close"  color="#909399" size="30"></uv-icon>
					</view>
				</view>
				<uv-search margin="30rpx 20rpx" shape="square" v-model="keyword" :show-action="false" :clearabled="true"  placeholder="输入客户名称搜索" @change="onSearch"></uv-search>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;" @scrolltolower="reachBottom">
					<view class="list">
						<block v-if="customerList.length > 0">
							<view class="mb-4">
								<view class="item flex" v-for="(item,index) in customerList" :key="index" @click="onItem(item,index)">
									<view class="title">{{item.name}}</view>
									<view class="check-icon">
										<uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
									</view>
								</view>
							</view>
							<uv-load-more :status="listStatus" ></uv-load-more>
						</block>
						<uv-empty text="暂无数据" v-else  mode="list"></uv-empty>
					</view>
				</scroll-view>
			</view>
		</uv-popup>
		<!-- 跟进时间选择 -->
		<uv-datetime-picker ref="datetimePicker" v-model="timeValue" mode="datetime" @confirm="createTimeChange"></uv-datetime-picker>
	</view>
</template>

<script setup>
import {
  ref,
  unref,
  computed
} from 'vue'
import { onLoad,onShow } from '@dcloudio/uni-app'
import {
  getCustomerListPage,
  createContact,
  getContacts,
  updateContact
} from '@/api/customer'
import AddressSelect from '@/components/AddressSelect/index.vue'
import { formatDateTime,prePage } from '@/utils/util'
const title = ref('添加联系人')
const listStatus = ref('loadmore')
const page = ref(1)
const pageSize = ref(10)
const keyword = ref('')
const lastPage = ref(false)
const customerList = ref([])
const customerName = ref('')
const type = ref('add')
const contactsId = ref(0)
const birthdayName = ref('')
const nextTime = ref('')
const content = ref('')
const contactsData = ref({})
const form = ref({
	customerId: 0,
	name: '',
	sex: -1.,
	decision: -1,
	customerName: ''
	
})
const errorType = ref('message')
const sexList = ref([
	{
		name: -1,
		text: '未知',
	},
	{
		name: 1,
		text: '男',
	},
	{
		name: 0,
		text: '女',
	},
])
const typeList = ref([
	{
		name: -1,
		text: '未知',
	},
	{
		name: 1,
		text: '是',
	},
	{
		name: 0,
		text: '否',
	},
])
const rules = ref({
	customerName: [
		{
			required: true,
			message: '请选择客户',
			trigger: ['change','blur']
		},
	],
	name: [
		{
			required: true,
			message: '请填写姓名',
			trigger: ['change','blur']
		},
	]
})


onLoad((e) => {
	console.log('e:',e)
	
	if(e.type == 'edit'){
		type.value = 'edit'
		contactsId.value = e.id
		title.value = '编辑联系人'
		getInfo()
	}else{
		if(e.id){
			form.value.customerName = e.name
			form.value.customerId = e.id
		}
	}
	getCustomerList()
})

const selectShowRef = ref()
const selectShow = () => {
	unref(selectShowRef).open()
}
const selectShowClose = () => {
	unref(selectShowRef).close()
}

const dateShowRef = ref()
const dateShow = () => {
	unref(dateShowRef).open()
}

const change = (e) => {
	form.value.birthday = e.value
	birthdayName.value = formatDateTime(e.value)
}

const datetimePicker = ref()
const createTimeShow = () => {
	unref(datetimePicker).open()
}
const createTimeChange = (e) => {
	form.value.nextTime = e.value
	nextTime.value = formatDateTime(e.value)
}

// 搜索
const onSearch = () => {
	page.value = 1
	lastPage.value = false
	getCustomerList()
}
// 获取联系人详情
const getInfo = async() => {
	form.value = await getContacts({id:contactsId.value})
}

// 页面数据
const getCustomerList = async(isNextPage,pages) => {
	await getCustomerListPage({
		pageNo: page.value,
		pageSize: pageSize.value,
		relation: 'my',
		name:keyword.value,
	}).then(res => {
		if(res) {
			// 不够一页
			if (res.list.length < 10) {
				listStatus.value = 'nomore'
			}
			// 最后一页
			if(res.list.length == 0) {
				lastPage.value = true
			} 
			// 第二页开始
			if(isNextPage) {
				customerList.value = customerList.value.concat(res.list)
				return 
			}
			customerList.value = res.list
			
			if(form.value.customerId) {
				customerList.value.forEach((item,index) => {
					if(form.value.customerId == item.id) {
						item.checked = true
						customerName.value = item.name
					} else {
						item.checked = false
					}
				})
			}
		}
	})
}

// 滚动到底部加载更多
const reachBottom = () => {
	if(lastPage.value || listStatus.value == 'loading') return 
	listStatus .value= 'loading'
	setTimeout(() => {
		getCustomerList(true,++page.value)
		if(customerList.value.length >= 10) {
			listStatus.value = 'loadmore';
		}else{
			listStatus.values = 'loading';
		} 
	}, 1200)
}
// 选择客户
const onItem = (val,i) => {
	customerList.value.forEach((item,index) => {
		if(val.id == item.id) {
			item.checked = true
			val.name=val.name?val.name:item.name;
		} else {
			item.checked = false
		}
	})
	form.value.customerId = val.id
	//customerId.value = val.id
	form.value.customerName = val.name ? val.name : ''
	selectShowClose()
}


// 提交跟进
const uForm = ref()
const submit = () => {
	console.log('form.value:',form.value)
	uForm.value.validate().then(res => {
		onSubmit()
	}).catch(errors => {
		uni.showToast({
			icon: 'error',
			title: '校验失败'
		})
	})
}
// 修确认提交
const onSubmit = async() => {
	//console.log()
	if(type.value == 'add'){
		await createContact(form.value)
		
		// 提示
		uni.showToast({
			title: "添加成功",
			icon: 'success',
			duration: 2000
		})
		
		setTimeout(() => {
			uni.navigateBack()
		}, 1000)
	}else{
			await updateContact(form.value)
			
			// 提示
			uni.showToast({
				title: "修改成功",
				icon: 'success',
				duration: 2000
			})
			
			setTimeout(() => {
				uni.navigateBack()
			}, 1000)
	}

}


</script>

<style lang="scss" scoped>
.set-box {
	padding: 0rpx 22rpx 250rpx;
  .option {
    .text {
      color: #747474;
      font-size: 26rpx;
      text-align: justify;
      padding-bottom: 15rpx;
    }
    .input-box {
      width: 200rpx;
      margin-right: 15rpx;
    }
  }
 }
 .popup-content {
	.popup-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: relative;
		font-size: 35rpx;
		font-weight: 600;
		text-align: center;
		height: 50px;
		padding-right: 25rpx;
	}
	.list {
		padding-bottom: 45rpx;
		.item {
			padding: 0 25rpx;
			justify-content: space-between;
			height: 55px;
			.title {
				flex: 1;
				font-size: 28rpx;
				font-weight: 600;
			}
			.check-icon {
				text-align: center;
				width: 100rpx;
			}
		}
	}
	.bottom_btn {
		display: flex;
		justify-content: flex-end;
		padding: 28rpx 10rpx 45rpx;
	}
}
.bottom-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 25rpx 30rpx 45rpx;
	background-color: #fff;
	z-index: 100;
}
</style>
